package com.giscloud.upload.controller;

import com.giscloud.commons.model.Result;
import com.giscloud.upload.entity.Attachment;
import com.giscloud.upload.service.AttachmentService;
import com.giscloud.upload.service.StorageService;
import eu.medsea.mimeutil.MimeUtil;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Collection;

/**
 * 文件上传
 * @Classname UploadController
 * @Description 文件操作控制器
 * @Date 2020/6/4 19:28
 * @Created by gis
 */
@RestController
@RequestMapping("/file")
@Log4j2
public class UploadController {
    @Autowired
    private StorageService storageService;
    @Autowired
    private AttachmentService attachmentService;

    /**
     * 上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Result<Attachment> upload(@RequestParam("file") MultipartFile file) throws IOException {
        return storageService.store(file.getInputStream(), file.getSize(), file.getContentType(), file.getOriginalFilename());
    }
    /**
     * 访问存储对象
     *
     * @param key 存储对象key
     * @return
     */
    @SneakyThrows
    @GetMapping("/fetch/{key:.+}")
    public ResponseEntity<Resource> fetch(@PathVariable String key) {
        if (key == null) {
            return ResponseEntity.notFound().build();
        }
        if (key.contains("../")) {
            return ResponseEntity.badRequest().build();
        }
        Resource file = storageService.loadAsResource(key);
        MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
        Collection<?> mimeTypes  = MimeUtil.getMimeTypes(file.getURL());
        MediaType mediaType = MediaType.parseMediaType(mimeTypes.toString());
        if (file == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok().contentType(mediaType).body(file);
    }

    /**
     * 下载存储对象
     *
     * @param key 存储对象key
     * @return
     */
    @SneakyThrows
    @GetMapping("/download/{key:.+}")
    public ResponseEntity<Resource> download(@PathVariable String key) {
        if (key == null) {
            return ResponseEntity.notFound().build();
        }
        if (key.contains("../")) {
            return ResponseEntity.badRequest().build();
        }
        Resource file = storageService.loadAsResource(key);
        MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
        Collection<?> mimeTypes  = MimeUtil.getMimeTypes(file.getURL());
        MediaType mediaType = MediaType.parseMediaType(mimeTypes.toString());
        if (file == null) {
            return ResponseEntity.notFound().build();
        }
        Attachment attachment = attachmentService.getByKey(key);
        return ResponseEntity.ok().contentType(mediaType).header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=" + URLEncoder.encode(attachment.getAttachmentName(), "UTF-8")).body(file);
    }
}
